import axios from "axios";
import VueCookies from "vue-cookies";
import store from "@/store/store";
import { Toast } from "vant";
import router from "@/router/index.js";
import utils from "./utils";

const server = axios.create({
  headers: {
    "Content-Type": "application/json;charset=UTF-8"
  }
});

// server.defaults.baseURL = '/api';

/* 在axios请求拦截器里配置token验证 */
server.interceptors.request.use(config => {
  config.cancelToken = new axios.CancelToken(c => {

    if (window.__axiosPromiseArr) {
      window.__axiosPromiseArr.push({ c });
    } else if (window.__axiosPromiseArr === undefined) {
      window.__axiosPromiseArr = [];
      window.__axiosPromiseArr[0] = { c };
    }
  });
  
  return Promise.resolve(config);
});

/* 在axios响应拦截器里获取token */

server.interceptors.response.use(
  response => {
    let code = response.data.code;
    if (response.headers.Authorization !== undefined) {
      VueCookies.set("Authorization", response.headers.Auth_token, "30d");
    }
    
    // 用户没有token 或者 token已经过期
    if (code === 500) {
      // api.userLogin();
    }
    return Promise.resolve(response.data);
  },
  error => {
    console.log(error);
    return Promise.reject(error);
  }
);

export default server;
